package member

import (
    "fmt"
    "time"
	"strings"
	"dhfshop/controllers/base"
	"dhfshop/models/member"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
	jwt "github.com/dgrijalva/jwt-go"
	TM "github.com/solarhell/tt-miniprogram"
)

// 头条会员管理
type TtMemberController struct {
	base.BaseController
}

// 小程序登陆接口
func (this *TtMemberController) TtAppLogin() {
	var (
	    ttMembers *member.TtMember = new(member.TtMember)
	)
	v := struct {
		PartnerId int64  `form:"-"`
		AppId     string `form:"app_id" valid:"Required"`
		Code      string `form:"code" valid:"Required"`
		AnonCode  string `form:"anonCode"`
	}{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	appid := "tt52f42449cdde6a19"
	secret := "54a19ac45c3d2f2da4b2497fe53bb2f7fe4f3ee3"
	ui, err := TM.Login(appid, secret, v.Code, v.AnonCode)
	if err != nil {
	   beego.Debug(err.Error())
	   this.ServeError(err.Error())
	   return
	}
	ttMembers, err = member.GetTtMemberByOpenId(ui.Openid); 
    if err != nil { //注册用户
		memberId, err := member.CreateMember(0,ui.Openid,ui.Openid)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
		ttMembers = new(member.TtMember)
		ttMembers.SessionKey = ui.SessionKey
		ttMembers.Openid = ui.Openid
		ttMembers.AnonymousOpenid = ui.AnonymousOpenid
		ttMembers.MemberId = memberId
		if _, e := member.AddTtMember(ttMembers); e != nil {
			this.ServeError(e.Error())
			return
		}
	}else{
		ttMembers.SessionKey = ui.SessionKey
		member.UpdateTtMemberByOpenId(ttMembers, "session_key")
	}
	token := jwt.New(jwt.GetSigningMethod("HS256"))
	claims := token.Claims.(jwt.MapClaims)
	//
	claims["CurrentUser"] = struct {
		Id        int
		CompanyId int
		Role      int
		AppId     string
	}{Id:int(ttMembers.MemberId), CompanyId:int(v.PartnerId), Role:1, AppId:v.AppId}
	claims["exp"] = time.Now().UTC().Add(time.Hour * 24 * 1).Unix()
	tokenSecret := beego.AppConfig.String("AuthTokenSecret")
	tokenString, err := token.SignedString([]byte(tokenSecret))
	if err != nil {
		this.ServeError("登录失败，请稍后再试")
		return
	}
	memberIdStr := fmt.Sprintf("%d", ttMembers.MemberId)
	this.Data["json"] = map[string]string{
		"member_id": memberIdStr,
		"token":     tokenString,
	}
	this.ServeJSON()
}

func (this *TtMemberController) TtBasicPut() {
	v := struct {
		AppId          string `form:"app_id" valid:"Required"`
		NickName       string `form:"nick_name"`
		AvatarUrl      string `form:"avatar_url"`
		EncryptedData  string `form:"encryptedData"`
		Iv             string `form:"iv"`
	}{}
	this.ParseForm(&v)
	valid := validation.Validation{}
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return 
	}
	curSysRoleId := this.Ctx.Input.GetData("curRoleId").(int) 
	curUserId := int64(this.Ctx.Input.GetData("curUserId").(int))
	encrypted_data := strings.Replace(v.EncryptedData, " ", "", -1)
	iv := strings.Replace(v.Iv, " ", "", -1)
	if len(encrypted_data) > 10 && len(iv) > 2 {
		//beego.Debug("member_id:",curUserId,encrypted_data,iv)
		sessionKey := ""
		if curSysRoleId == 1 {
	        if tTmember, err := member.GetTtMemberByMemberId(curUserId); err == nil {
				sessionKey = tTmember.SessionKey
			}
		} else {
		   beego.Debug("cur sys role is invalid")
		}
		if len(sessionKey) < 5 {
			beego.Debug("member_id:", curUserId, "session key is invalid")
			this.ServeError(fmt.Sprintf("session key is invalid, user_id:", curUserId))
			return
		}
		//beego.Debug("member_id:", curUserId, "sessionKey:", sessionKey)
		userInfo, err := TM.DecryptUserInfo("",encrypted_data,"",iv,sessionKey)
		if err != nil {
			beego.Debug("member_id:", curUserId, "err:", err.Error())
			this.ServeError(err.Error())
			return
		}
		if curSysRoleId == 1 {
	        tTmembers := &member.TtMember{MemberId:curUserId,Nickname:userInfo.Nickname,Avatar:userInfo.Avatar,Gender:userInfo.Gender,
			                Country:userInfo.Country,Province:userInfo.Province,City:userInfo.City}
			if err := member.UpdateTtMemberByMemberId(tTmembers,"nick_name","avatar","gender","country","province","city"); err != nil {
				this.ServeError(err.Error())
				return
			}
		} else {
		   beego.Debug("cur sys role is invalid")
		}
	}
	rsp := struct {
		UserId    int64       `json:"user_id"`
		OpenId    string      `json:"open_id"`
	    Modified  time.Time   `json:"modified"`
	}{UserId:curUserId,OpenId:"",Modified:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

